<script setup lang="ts" name="PageScroll">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useKeepAliveStoreWithOut } from '@/store/modules/keepAlive'
import { useTagCacheStoreWithOut } from '@/store/modules/tag'
import { clearPending } from '@/utils/axios/cancelToken'
import { propTypes } from '@/utils/propTypes'
const route = useRoute()
const { t } = useI18n() // 国际化

const appStore = useAppStoreWithOut()
const { systemConfig, pageLoading } = storeToRefs(appStore)

const keepAliveStore = useKeepAliveStoreWithOut()
const { scrollPosition, scrollTopHeight } = storeToRefs(keepAliveStore)

const tagCacheStore = useTagCacheStoreWithOut()
const { tagList } = storeToRefs(tagCacheStore)

const scrollbarRef: any = ref(null)

const { getPrefixCls, variables } = useDesign()
const prefixCls = getPrefixCls('page-wrap')
const pageScrollContent = getPrefixCls('page-scroll-content')
const scrollWrap = getPrefixCls('scroll-wrap')

defineProps({
  noPadding: propTypes.bool.def(false)
})

// 滚动监听执行事件
const handleScroll = (e) => {
  scrollTopHeight.value = e.scrollTop
}

// 路由跳转前执行事件
onBeforeRouteLeave(() => {
  const hasTag = tagList.value.some((item: any) => {
    return item.path === route.fullPath
  })
  if (hasTag && systemConfig.value && systemConfig.value.isKeepAlive && route.meta.keepAlive) {
    keepAliveStore.setScrollPosition({
      name: route.name,
      fullPath: route.fullPath,
      savedPosition: scrollTopHeight.value
    })
  }
  clearPending()
})

// 在组件挂载到页面后执行
onMounted(() => {
  scrollTopHeight.value = 0
})

// keep-alive启用时，页面被激活时使用
onActivated(() => {
  if (systemConfig.value.isKeepAlive && route.meta.keepAlive) {
    let hasRoute = false
    if (scrollPosition.value.length > 0) {
      scrollPosition.value.forEach((item: any) => {
        if (item.fullPath === route.fullPath) {
          hasRoute = true
          scrollbarRef.value.scrollTo(0, item.savedPosition)
        }
      })
      if (!hasRoute) {
        scrollbarRef.value.scrollTo(0, 0)
      }
    }
  }
})
</script>

<template>
  <ElScrollbar ref="scrollbarRef" v-loading="pageLoading && systemConfig.loadingType === 'content'" :wrap-class="scrollWrap" :view-class="[variables.namespace + '-scroll-view']" :class="prefixCls" @scroll="handleScroll">
    <div :class="[pageScrollContent, noPadding ? 'no-padding' : '', systemConfig.isFooterEnable ? 'is-footer' : '']">
      <slot />
    </div>
    <Footer v-if="systemConfig.isFooterEnable" />
    <ElBacktop :title="t('common', 'backTop')" :target="'.' + scrollWrap" />
  </ElScrollbar>
</template>

<style scoped lang="scss">
$prefix-cls: #{$namespace}-page-wrap;

.#{$prefix-cls} {
  display: flex;
  flex-direction: column;
}

.#{$namespace}-page-scroll-content {
  padding: var(--el-space);

  &.no-padding{
    padding: 0;
  }
}
</style>
